package com.zyz.M_File和IO流.IO流.练习;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author: vick
 * @Date: 2025/4/10
 * @Description:
 * @version: 1.0
 */
public class LoginSystem {

    private static final String DB_File = "db.txt";
    private static final int MAX_ATTEMPTS = 3;
    private static final int BLOCK_TIME = 30;

    //读取数据库文件
    /*
    * key 李四 ==>  set ==> 唯一性
    * value:  [654321,3,1715662302]
    * 账号|密码|密码可以错误的次数|时间戳
    * 李四|654321|3|1715662302
    * */
    public static Map<String, String[]> getDB() {
        HashMap<String, String[]> db = new HashMap<>();
        BufferedReader bufferedReader = null;
        try {
            File file = new File(DB_File);
            FileReader fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String[] split = line.split("\\|");
                if (split.length == 4) {
                    String username = split[0];
                    String[] info = new String[3];
                    System.arraycopy(split,1,info,0, 3);
                    db.put(username, info);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return db;
    }

    //将用户信息写入数据库文件
    public static void writeDB(Map<String, String[]> db) {
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File(DB_File);
            FileWriter fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);
            for (Map.Entry<String, String[]> entry : db.entrySet() ) {
                String username = entry.getKey();
                String[] info = entry.getValue();
                String line = username + "|" + String.join("|", info) + "\n";
                bufferedWriter.write(line);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    //显示菜单
    private static void printMenu() {
        System.out.println("===请选择===");
        System.out.println("    1. 登录");
        System.out.println("    2. 注册");
        System.out.println("==========");
    }

    //处理菜单
    private static boolean menu() {
        printMenu();
        Scanner scanner = new Scanner(System.in);
        String num = scanner.nextLine();
        if ("1".equals(num) || "2".equals(num)) {
            System.out.print("输入用户名：");
            String username = scanner.nextLine();
            System.out.print("输入密码：");
            String password = scanner.nextLine();
            switch (num) {
                case "1" :
                    //登录
                    return login(username, password);
                case "2":
                    //注册
                    return register(username, password);
                default:
                    System.out.println("无效操作");
            }
        }else {
            System.out.println("无效操作");
            return false;
        }
        return false;
    }

    //登录
    private static boolean login(String username, String password) {
        Map<String, String[]> db = getDB();
        //判断账号
        if (db.containsKey(username)) {
            String[] userInfo = db.get(username);
            //可错误次数
            int attempts = Integer.parseInt(userInfo[1]);
            //封禁到期时间
            long blockTime = Long.parseLong(userInfo[2]);

            //判断账号是否被封禁
            if (attempts == 0) {
                //判断是否解封
                if (blockTime <= System.currentTimeMillis()/1000) {
                    //解封账号，重置尝试次数
                    userInfo[1] = String.valueOf(MAX_ATTEMPTS);
                    writeDB(db);
                    return login(username, password);
                }else {
                    long remainingTime = blockTime - System.currentTimeMillis() / 1000;
                    System.out.println("账号以封禁，还剩" + remainingTime + "秒");
                    return false;
                }
            }else {
                //判断密码
                if (password.equals(userInfo[0])) {
                    //登录成功，重置尝试次数
                    userInfo[1] = String.valueOf(MAX_ATTEMPTS);
                    writeDB(db);
                    System.out.println("登录成功!欢迎：" + username);
                    return true;
                }else {
                    if (attempts == 1) {
                        //最后一次尝试失败，封禁账号
                        userInfo[1] = "0";
                        userInfo[2] = String.valueOf(System.currentTimeMillis() / 1000 + BLOCK_TIME);
                        writeDB(db);
                        System.out.println("密码错误！账号封禁30秒");
                    }else {
                        userInfo[1] = String.valueOf(attempts - 1);
                        writeDB(db);
                        System.out.println("密码错误！ 还剩" + userInfo[1] + "次机会");
                    }
                    return false;
                }
            }
        }else {
            System.out.println("用户名不存在");
            return false;
        }
    }

    //注册
    private static boolean register(String username, String password) {
        Map<String, String[]> db = getDB();
        if (db.containsKey(username)) {
            System.out.println("用户名已存在");
            return false;
        }

        //添加到hashmap中
        db.put(username, new String[]{password, String.valueOf(MAX_ATTEMPTS), String.valueOf(System.currentTimeMillis() / 1000)});
        //写入文件中
        writeDB(db);
        return true;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            boolean result = menu();
            if (result) {
                System.out.println("是否继续操作？（Y/N）");
                String choice = scanner.nextLine().trim().toUpperCase();
                if (!"Y".equals(choice)) {
                    System.out.println("感谢使用，再见！");
                    break;
                }
            }
        }
    }
}
